package com.lagou.rpc.handler;

import com.lagou.request.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;


/**
 * 客户端事件处理器UserClientHandler
 *
 * @author thresh
 * @date 2021/2/22 21:18
 */
public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable<Object> {

    // 定义上下文对象
    private ChannelHandlerContext channelHandlerContext;

    private Object result;

    private RpcRequest params;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channelHandlerContext = ctx;
        super.channelActive(ctx);
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        result = msg.toString();
        notify();
    }

    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    public synchronized Object call() throws Exception {
        channelHandlerContext.writeAndFlush(params);
        wait();
        return result;
    }

    public void setParams(RpcRequest params) {
        this.params = params;
    }
}
